//
//  ToolCleanCache.swift
//  Library_y
//
//  Created by JC on 2023/6/6.
//

import Foundation

public extension Tools {
    
    /// 获取APP缓存
    static func getCacheSize()-> Double {
        // 取出cache文件夹目录
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else { return 0 }
        // 取出文件夹下所有文件数组
        guard let fileArr = FileManager.default.subpaths(atPath: cachePath) else { return 0 }
        // 快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr {
            // 把文件名拼接到路径中
            let path = cachePath + ("/\(file)")
            // 取出文件属性
            guard let floder = try? FileManager.default.attributesOfItem(atPath: path) else { return 0 }
            // 用元组取出文件大小属性
            for (key, fileSize) in floder {
                // 累加文件大小
                if key == FileAttributeKey.size {
                    size += (fileSize as AnyObject).integerValue
                }
            }
        }
        let totalCache = Double(size) / 1024.00/1024.00
        return totalCache
    }
    
    
     /// 清理APP缓存
    static func clearCache() {
        // 取出cache文件夹目录
        guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else { return }
        // 取出文件夹下所有文件数组
        guard let fileArr = FileManager.default.subpaths(atPath: cachePath) else { return }
        // 遍历删除
        for file in fileArr {
            let path = (cachePath as NSString).appending("/\(file)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                    
                }
            }
        }
    }
}
